package com.hclink.website.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hclink.website.model.Menus;
import com.hclink.website.model.MenusPv;
import com.hclink.website.model.User;
import com.hclink.website.service.MenusService;
import com.hclink.website.util.RedisUtils;
import com.hclink.website.util.Result;
import com.hclink.website.util.validAction.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("api/menus")
@Controller
public class MenusController extends BaseController {
	@Resource
	private MenusService menusService;
	@Resource
	private RedisUtils redisUtils;
	@Value("${redisopen}")
	private Integer redisopen;// 必须存在的

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result<Integer> add(@Validated(CreateAction.class) Menus record, BindingResult bindingResult,
                               Result<Integer> result) {
		String msg = this.Validate(bindingResult);
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		result.setData(menusService.insertSelective(record));
		setridesmen();
		return result;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Result<Integer> edit(@Validated(UpdateAction.class) Menus record, BindingResult bindingResult,
                                Result<Integer> result) {
		String msg = this.Validate(bindingResult);
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		result.setData(menusService.updateByPrimaryKeySelective(record));
		if(redisopen==1) {
			setridesmen();
		}

		return result;
	}

	@RequestMapping(value = "/sla", method = RequestMethod.POST)
	@ResponseBody
	public Result<List<Menus>> sla(String type,Result<List<Menus>> result) {
		Map<String, String> map = new HashMap<String, String>();
		if(null!=type && !type.isEmpty()){
			map.put("type", type);
		}
		map.put("other", "state in (1,0) ");
		map.put("orderBy", "parentid asc,sort ASC");
		List<Menus> list = menusService.selectAll(map);
		result.setData(list);
		return result;
	}

	@RequestMapping(value = "/spv", method = RequestMethod.POST)
	@ResponseBody
	public Result<List<MenusPv>> spv(Integer uid,Result<List<MenusPv>> result, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		StringBuilder sb = new StringBuilder();
		sb.append("state in (1,0)");
		if(null!=uid && uid>0){
			map.put("uid", ""+uid);
		}else {
			User user = (User) request.getSession().getAttribute("user");
			if(user.getGroupid()!=1){
				map.put("uid", "" + user.getUserid());
				sb.append(" and find_in_set(t_menus.menusId,")
						.append("(select group_concat(distinct replace(concat_ws(',',replace(m.path,'/',','),m.menusId),'/',',') order by m.menusId) mpth"
						+ " from t_upv p join t_menus m on m.menusId=p.mid and (p.pv & 1)>0 and p.uid=")
						.append(user.getUserid()).append("))");
			}
		}
		map.put("other", sb.toString());
		map.put("orderBy", "parentid asc,sort ASC");
		List<MenusPv> list = menusService.selectAllasPv(map);
		result.setData(list);
		return result;
	}

	@RequestMapping(value = "/apv", method = RequestMethod.POST)
	@ResponseBody
	public Result<Integer> apv(String dls, Result<Integer> result, HttpServletRequest request) {
		JSONArray ls;
		String msg = null;
		try{
			ls= JSONArray.parseArray(dls);
		} catch (Exception e) {
			ls=null;
			msg=e.toString();
		}
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		if(ls.isEmpty()){
			result.setCode(1);
			result.setMsg("栏目列表不能为空");
			return result;
		}
		//User user=(User)request.getSession().getAttribute("user");
		//menusService.deleteMenusPvByUserid(JSONObject.parseObject(user.getUserid());
		menusService.deleteMenusPvByUserid(JSONObject.parseObject(ls.get(0).toString()).getInteger("uid"));
		int n=0;
		for(Object o:ls){
			JSONObject pv= JSONObject.parseObject(o.toString());
			Map m=new HashMap();
			m.put("menusid",pv.get("menusid"));
			//m.put("uid",user.getUserid());
			m.put("uid",pv.get("uid"));
			m.put("pv",pv.get("pv"));
			n+=menusService.insertMenusPv(m);
		}
		result.setData(n);
		result.setOk(n>=ls.size());
		return result;
	}

	@RequestMapping(value = "/editsort", method = RequestMethod.POST)
	@ResponseBody
	public Result<Integer> editsort(@Validated(EditsortAction.class) Menus record, String menusIds,
                                    BindingResult bindingResult, Result<Integer> result) {
		String msg = this.Validate(bindingResult);
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		Integer parentid = record.getParentid();
		String path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		if (parentid == 0) {
			path = "0";
		} else {
			Menus menusMap = menusService.selectByPrimaryKey(parentid);
			path = menusMap.getPath() + "/" + parentid;
		}
		String[] menusStrings = menusIds.split(",");
		String sql = "( case ";
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < menusStrings.length; i++) {
			System.out.println(menusStrings[i]);
			if (Integer.parseInt(menusStrings[i]) < 1) {
				result.setCode(1);
				result.setMsg("栏目ID错误");
				return result;
			}
			list.add(Integer.parseInt(menusStrings[i]));
			sql = sql + " when menusId = " + menusStrings[i] + " then " + (i + 1);
		}
		sql = sql + "  end)";
		map.put("parentid", parentid);
		map.put("path", path);
		map.put("other", sql);
		map.put("list", list);
		result.setData(menusService.updateByMenusId(map));
		if(redisopen==1) {
			setridesmen();
		}

		return result;
	}

	@RequestMapping(value = "/editState", method = RequestMethod.POST)
	@ResponseBody
	public Result<Integer> editState(@Validated(EditstateAction.class) Menus record, BindingResult bindingResult,
                                     Result<Integer> result) {
		String msg = this.Validate(bindingResult);
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		result.setData(menusService.updateByPrimaryKeySelective(record));
		if(redisopen==1) {
			setridesmen();
		}

		return result;
	}

	@RequestMapping(value = "/selectById", method = RequestMethod.POST)
	@ResponseBody
	public Result<Menus> selectById(@Validated(SelectIdAction.class) Menus record, BindingResult bindingResult,
                                    Result<Menus> result) {
		String msg = this.Validate(bindingResult);
		if (msg != null) {
			result.setCode(1);
			result.setMsg(msg);
			return result;
		}
		Integer menusid = record.getMenusid();
		result.setData(menusService.selectByPrimaryKey(menusid));
		return result;
	}

	public void setridesmen() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("other", "state in (1) ");
		map.put("orderBy", "parentid asc,sort ASC");
		List<Menus> menus = menusService.selectAll(map);
		redisUtils.set("menues", menus);
	}
}
